import fetch from '../utils/fetch.js'
import {Api},Actions from '../constants'



export function switchAllocation(plan) {
    return {
        type:Actions.SWITCH_ALLOCATION,
        currentPlan:plan
    }
}
export function toggleAllocation(stg_name){
    return (dispatch,getState) =>{
        return dispatch(switchAllocation(getState()[stg_name]))
    }
}

export function requestAllocation(payload){
    return {
        type:Actions.REQUEST_ALLOCATION,
        payload
    }
}
function receiveAllocation(plans) {
    return {
        type:Actions. RECEIVE_ALLOCATION,
        plans
    }
}


function fetchTwoAllocation(params,hasCurrentPlan) {
    return dispatch => {
        dispatch(requestAllocation({loading:true}))
        return fetch(Api.showTwoAlloction)
            .then(json => {
                let plans = json.body;
                if(!hasCurrentPlan){
                    plans.currentPlan = plans.userPlan?plans.userPlan:plans.sysPlan;
                }
                dispatch(requestAllocation({loading:false,loaded:true}))
                dispatch(receiveAllocation(plans))
            })
            .catch(err => {
                dispatch(requestAllocation({loading:false,loaded:false}))

            })
    }
}
function shouldFetchTwoAllocation(state,hasPlan) {
    let currentPlan = state.currentPlan;
    if (!currentPlan) {
        return true
    }
    return false;
}
export function fetchTwoAllocationIfNeeded(plan) {
    return (dispatch, getState) => {
        let cstate = getState()
        if (shouldFetchTwoAllocation(cstate, !!cstate.currentPlan)) {
            return dispatch(fetchTwoAllocation(plan))
        }
    }
}


function shuldFetchQuickAllocation(state,hasQuickPlan){
    let sysPlan = state.sysPlan;
    if (!sysPlan) {
        return true
    }
    return false;
}
export function fetchQuickAllocation(){
    return (dispatch, getState) => {
        dispatch(requestAllocation({loading:true}))
        return fetch(Api.quickAllocation)
            .then(json => {
                dispatch(requestAllocation({loading:false,loaded:true}))
                dispatch(receiveAllocation(json))
            })
            .catch(err => {
                dispatch(requestAllocation({loading:false,loaded:false}))
            })
    }
}




// 保存调整后的配置方案
export function saveAllocation(state){
    return {
        type:Actions.SAVE_ALLOCATION,
        state
    }
}
export function postAllocation(params){
    return (dispatch, getState) => {
        dispatch(requestAllocation({loading:true}))
        return fetch(Api.saveAllocation)
            .then(res => {
                dispatch(requestAllocation({loading:false,loaded:true}))
                dispatch(saveAllocation(getState()))
            })
            .catch(err => {
                dispatch(requestAllocation({loading:false,loaded:false}))
            })
    }
}
